﻿using Enum;
using MediatR;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.UserW
{
    public class UserCreateHandler : IRequestHandler<UserCreateCommand, Result>
    {
        public readonly IBaseRepository<Users> UsersRepository;
        public readonly IBaseRepository<UserRole> UserRoleRepository;

        public UserCreateHandler(IBaseRepository<Users> usersRepository, IBaseRepository<UserRole> userRoleRepository)
        {
            UsersRepository = usersRepository;
            UserRoleRepository = userRoleRepository;
        }

        public async Task<Result> Handle(UserCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Added };
            int i = 0;
           
            try
            {
                var res = new Users()
                {
                    UserName = request.UserName,
                    Pwd = request.Pwd,
                };
                UsersRepository.Add(res);
                foreach (var item in request.RoleId)
                {
                    var query = new UserRole()
                    {
                        UserId = res.UserId,
                        CreateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                        RoleId = item
                    };
                  
                    UserRoleRepository.Add(query);
                }



                if (res != null)
                {
                    result.Code = (int)CommonEnumCode.Success;
                }

            }
            catch (Exception)
            {

                result.Msg = "用户添加失败";
            }
            return result;
        }
    }
}
